package toolsKit.csv;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CsvFile07 extends AbstractAdvanceCsvFile {

	private CsvFile07() {
		super();
	}

	public CsvFile07(File file) {
		this(file, DEFAULT_SEPARATOR);
	}
	
	public CsvFile07(File file, char separator) {
		
		this();
		
		if (file == null) {
			throw new IllegalArgumentException("Le fichier file ne peut pas �tre null");
		}

		this.file = file;

		if (!isValidSeparator(separator)) {
			throw new IllegalArgumentException("Le s�parateur sp�cifi� n'est pas pris en charge.");
		}

		this.separator = separator;
		// Init
		init();
	}

	private void init() {
		lines = CsvFileHelper.readFile(file);

		cleanLines();

		data = new ArrayList<String[]>(cleanedLines.size());

//		 final String regex =
//		 "(^|(?<=;))([^\";])*((?=;)|$)|((?<=^\")|(?<=;\"))([^\"]|\"\")*((?=\";)|(?=\"$))";
		final String regex = "(^|(?<=" + separator + "))([^\"" + separator + "])*((?=" + separator
				+ ")|$)|((?<=^\")|(?<=" + separator + "\"))([^\"]|\"\")*((?=\"" + separator + ")|(?=\"$))";
		Pattern p = Pattern.compile(regex);
		boolean first = true;
		for (String line : cleanedLines) {
			Matcher m = p.matcher(line);

			List<String> temp = new ArrayList<String>();
			while (m.find()) {
				temp.add(m.group());
			}

			String[] oneData = listToArray(temp);
			if (first) {
				titles = oneData;
				first = false;
			} else {
				data.add(oneData);
			}
		}

		mapData();
	}

	private String[] listToArray(List<String> liste) {
		String[] oneData = new String[liste.size()];
		for (int i = 0; i < oneData.length; i++) {
			oneData[i] = liste.get(i);
		}
		return oneData;
	}

	// GETTERS

}
